package com.yunkaweilai.android.fragment;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.shop.AddPtShopActivity;
import com.yunkaweilai.android.activity.shop.AddTimeShopActivity;
import com.yunkaweilai.android.activity.shop.PtShopActivity;
import com.yunkaweilai.android.activity.shop.TimeShopActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.base.BaseFragment;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.fragment.shop.CommodityTypeFragment;
import com.yunkaweilai.android.fragment.shop.TimeOutTypeFragment;
import com.yunkaweilai.android.model.AppRuleModel;
import com.yunkaweilai.android.model.login.UserInfoModel;
import com.yunkaweilai.android.model.shop.ShopModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.InputMethodUtils;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 商品界面
 * Created by Administrator on 2017-02-24.
 */

public class CommodityFragment extends BaseFragment implements RadioGroup.OnCheckedChangeListener {

    Unbinder unbinder;
    @BindView(R.id.id_rbtn_1)
    RadioButton idRbtn1;
    @BindView(R.id.id_rbtn_2)
    RadioButton idRbtn2;
    @BindView(R.id.id_group)
    RadioGroup idGroup;
    @BindView(R.id.id_shop_llayout)
    LinearLayout idShopLlayout;
    @BindView(R.id.id_search_rllayout)
    RelativeLayout idSearchRllayout;
    @BindView(R.id.id_listView_search)
    ListView idListViewSearch;
    @BindView(R.id.id_edt_search)
    EditText idEdtSearch;
    @BindView(R.id.id_img_clean)
    ImageView idImgClean;
    @BindView(R.id.id_view1)
    View idView1;
    @BindView(R.id.id_view2)
    View idView2;
    @BindView(R.id.id_shop_container)
    FrameLayout idShopContainer;
    @BindView(R.id.content_view)
    FrameLayout contentView;
    @BindView(R.id.titlebar_tv)
    TextView titlebarTv;
    @BindView(R.id.titlebar_iv_right_2)
    ImageView titlebarIvRight2;
    @BindView(R.id.titlebar_iv_right)
    ImageView titlebarIvRight;
    @BindView(R.id.titlebar_tv_right)
    TextView titlebarTvRight;
    @BindView(R.id.id_view_underline)
    View idViewUnderline;
    @BindView(R.id.rl_titlebar)
    RelativeLayout rlTitlebar;
    private int type = 0;
    private CommodityTypeFragment commodityTypeFragment;
    private TimeOutTypeFragment timeOutTypeFragment;
    private CommonAdapter<ShopModel.DataBean.ListBean> searchAdapter;
    private ArrayList<ShopModel.DataBean.ListBean> searchList = new ArrayList<>();
    private TitleBuilder titleBuilder;
    private AppRuleModel.DataBean.InfoBean appRuleModel;
    private UserInfoModel.DataBean.StoreEmployeeInfoBean userInfo;

    public void refresh() {
        idRbtn1.setChecked(true);
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        hideAllFragment(transaction);
        type = 0;
        rbCheck(true);
        if (commodityTypeFragment == null) {
            commodityTypeFragment = CommodityTypeFragment.newInstance();
            transaction.add(R.id.id_shop_container, commodityTypeFragment);
        } else {
            commodityTypeFragment.refresh();
            transaction.show(commodityTypeFragment);
        }
        idView1.setBackgroundColor(getResources().getColor(R.color.wjx_title_bg_next));
        idView2.setBackgroundColor(getResources().getColor(R.color.bottom_rgb_bule_false));
    }


    @Override
    public int getContentViewId() {
        return R.layout.fragment_commodity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        titleBuilder = new TitleBuilder(rootView);
        titleBuilder.setTitleText("商品")
                .setLeftImage(R.mipmap.ic_go_back)
                .setLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        idSearchRllayout.setVisibility(View.GONE);
//                        idShopLlayout.setVisibility(View.VISIBLE);
//                        idEdtSearch.setText("");
                        mAc.finish();
                    }
                });
        return rootView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
//        titlebarIvLeft.setVisibility(View.GONE);
        appRuleModel = BaseApplication.getAppRuleModel();
        userInfo = BaseApplication.getUserInfo();
        initAdapter();
        initClick();
        initView();
    }

    private void initAdapter() {
        searchAdapter = new CommonAdapter<ShopModel.DataBean.ListBean>(mAc, R.layout.item_list_shop_info, searchList) {
            @Override
            protected void convert(ViewHolder viewHolder, ShopModel.DataBean.ListBean item, int position) {
                viewHolder.setVisible(R.id.id_tv_tingyong, false);
                TextView tvname = viewHolder.getView(R.id.id_tv_name);
                if (type == 0) {
                    if (item.getStatus().equals("0")) {
//                    viewHolder.setVisible(R.id.id_tv_tingyong,true);
                        tvname.setText(Html.fromHtml(item.getGoods_name() + "    " + "<font color='#F53435'>" + "停用中" + "</font>"));
                    } else {
                        tvname.setText(item.getGoods_name() + "");
                    }
                }else {
                    if (item.getStatuss().equals("0")){
//                    viewHolder.setVisible(R.id.id_tv_tingyong,true);
                        tvname.setText(Html.fromHtml(item.getGoods_name() +"    "+ "<font color='#F53435'>" + "停用中" + "</font>" ));
                    }else {
                        tvname.setText(item.getGoods_name() + "");
                    }
                }

                viewHolder.setVisible(R.id.id_tv_duo, false);

                if (type == 0 && item.getSkuList().size() > 1) {
                    viewHolder.setVisible(R.id.id_tv_duo, true);
                }
                ImageView mIdImg = viewHolder.getView(R.id.id_img);
                Utils.shopInfoImg(mAc, item.getGoods_image(), mIdImg);

                viewHolder.setText(R.id.id_tv_price, item.getShow_shop_price() + "/" + item.getUnit());
                if (type == 0) {
                    viewHolder.setText(R.id.id_tv_info, "编号：" + item.getGoods_sku() + " 库存：" + item.getMay_use_stock());
                } else {
                    viewHolder.setText(R.id.id_tv_info, "编号：" + item.getGoods_sku());
                }
            }
        };
        idListViewSearch.setAdapter(searchAdapter);
    }

    private void initClick() {
        idEdtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((actionId == 0 || actionId == 3) && event != null && idEdtSearch.length() > 0) {
                    //点击搜索要做的操作
                    InputMethodUtils.closeSoftKeyboard(mAc);
                    if (type == 0) {
                        initSearch(Api.SHOP_INFO_LIST, idEdtSearch.getText().toString());
                    } else {
                        initSearch(Api.TIME_INFO_LIST, idEdtSearch.getText().toString());
                    }
                }
                return false;
            }
        });
        idEdtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0) {
                    idImgClean.setVisibility(View.GONE);
                    idSearchRllayout.setVisibility(View.GONE);
                    idShopLlayout.setVisibility(View.VISIBLE);
                    return;
                } else {
                    idImgClean.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        idListViewSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("20")) {
                    if (type == 0) {
                        PtShopActivity.actionStart(mAc, searchList.get(position).getId() + "");
                    } else {
                        TimeShopActivity.actionStart(mAc, searchList.get(position).getId() + "");
                    }
                }
            }
        });

    }

    private void initSearch(String url, String keyword) {
        HttpRequest.postUrl(url)
                .addParams("keyword", keyword)
                .addParams("ShowPage", "1")
                .addParams("PageSize", "20")
                .addParams("CurrPage", "1")
                .log(TAG).execute(new PostProcess.StringCallBack() {
            @Override
            public void onResponse(String json) {
                Gson gson = new Gson();
                boolean checkCode = Utils.checkCode(mAc, json);
                if (checkCode) {
                    ShopModel shopModel = gson.fromJson(json, ShopModel.class);
                    searchList.clear();
                    searchList.addAll(shopModel.getData().getList());
                    searchAdapter.notifyDataSetChanged();
                    if (searchList.size() > 0) {
                        idShopLlayout.setVisibility(View.GONE);
                        idSearchRllayout.setVisibility(View.VISIBLE);
                    } else {
                        showToast("暂无此商品");
                    }

                }
            }

            @Override
            public void onError(Exception e) {

            }
        });
    }


    private void initView() {
        if (userInfo.isIs_first() && (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("21"))) {
            titleBuilder.setRightText("新增商品");
            titlebarIvRight.setVisibility(View.VISIBLE);
        } else {
            titlebarIvRight.setVisibility(View.GONE);
        }
        idGroup.setOnCheckedChangeListener(this);
        idRbtn1.setChecked(true);
        rbCheck(true);
    }

    private void rbCheck(boolean flag) {
        if (flag) {
            if (userInfo.isIs_first() && (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("21"))) {
                titleBuilder.setRightText("新增商品");
                titlebarTvRight.setVisibility(View.VISIBLE);
            } else {
                titlebarTvRight.setVisibility(View.GONE);
            }
            idEdtSearch.setHint("请输入实物商品/条码");
        } else {
            if (userInfo.isIs_first() && (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("22"))) {
                titleBuilder.setRightText("新增计次");
                titlebarTvRight.setVisibility(View.VISIBLE);
            } else {
                titlebarTvRight.setVisibility(View.GONE);
            }
            idEdtSearch.setHint("请输入计次商品/条码");
        }
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public void hideAllFragment(FragmentTransaction transaction) {
        if (commodityTypeFragment != null) {
            transaction.hide(commodityTypeFragment);
        }
        if (timeOutTypeFragment != null) {
            transaction.hide(timeOutTypeFragment);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {

        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        hideAllFragment(transaction);
        switch (checkedId) {
            case R.id.id_rbtn_1:
                type = 0;
                rbCheck(true);
                if (commodityTypeFragment == null) {
                    commodityTypeFragment = CommodityTypeFragment.newInstance();
                    transaction.add(R.id.id_shop_container, commodityTypeFragment);
                } else {
                    commodityTypeFragment.refresh();
                    transaction.show(commodityTypeFragment);
                }
                idView1.setBackgroundColor(getResources().getColor(R.color.wjx_title_bg_next));
                idView2.setBackgroundColor(getResources().getColor(R.color.bottom_rgb_bule_false));
                break;
            case R.id.id_rbtn_2:
                type = 1;
                rbCheck(false);
                if (timeOutTypeFragment == null) {
                    timeOutTypeFragment = new TimeOutTypeFragment();
                    transaction.add(R.id.id_shop_container, timeOutTypeFragment);
                } else {
                    timeOutTypeFragment.refresh();
                    transaction.show(timeOutTypeFragment);
                }
                idView2.setBackgroundColor(getResources().getColor(R.color.wjx_title_bg_next));
                idView1.setBackgroundColor(getResources().getColor(R.color.bottom_rgb_bule_false));
                break;
        }
        transaction.commit();
    }


    @OnClick({R.id.titlebar_tv_right, R.id.id_img_clean})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titlebar_tv_right:

                if (type == 0) {
                    if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("21")) {
                        intent2Activity(AddPtShopActivity.class);
                    }
                } else {
                    if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("22")) {
                        intent2Activity(AddTimeShopActivity.class);
                    }
                }


                break;
            case R.id.id_img_clean:
                idImgClean.setVisibility(View.GONE);
                idEdtSearch.setText("");
                break;
        }
    }
}
